const {Book} = require('../../models/Books');
const {Commodity} = require('../../models/commodity')

module.exports = async (req, res) => {
    let opt = [
        {$match:{"ISBN": req.query.ISBN}},
        {
            $lookup:{
                from: "commodities",
                localField: "ISBN",
                foreignField: "ISBN",
                as: "list"
            },
        },
        {
            $project:{
                "ISBN":1,
                "title":1,
                "author":1,
                "publisher":1,
                "img":1,
                "list.Art_No":1,
                "list.customPrice":1,
                "list.appearance":1,
                "list.freight":1
            }
        },
        {$unwind:"$list"},
        
    ];
    let opt2 = [
        {$match:{"ISBN": req.query.ISBN}},
        {
            $lookup:{
                from: "users",
                localField: "user_id",
                foreignField: "user_id",
                as: "userInfo"
            },
        },
        {
            $project:{
                "userInfo.user_id":1,
                "userInfo.nickname":1,
                "userInfo.avatar":1,
                "userInfo.sex":1
            }
        },
        {$unwind:"$userInfo"},
    ]
    Book.aggregate(opt, (err, data) => {
        var recoms = [];
        if (err) {
            res.status(500).send({errCode:"1",msg:"服务器内部错误"})
        } else {
           recoms = recoms.concat(data)
           for(let i=0;i<data.length;i++){
               Object.assign(recoms[i],data[i].list)
               delete recoms[i].list;
           }
           Commodity.aggregate(opt2, (err,data) => {
                if(err){
                    res.status(500).send({errCode:"1",msg:"服务器内部错误"})
                }else{
                    for(let i=0;i<data.length;i++){
                        Object.assign(recoms[i], data[i].userInfo)
                    }
                    res.send({errCode:'0',msg:'请求成功',data:{commodityList:recoms}})
                }
           })
            }
        }
    );
}